package backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class combinationSum39 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList();
        dfs(candidates,0,target,result,new ArrayList<>());
        return result;

    }

    private void dfs(int[] candidates, int i,int target, List<List<Integer>> result, ArrayList<Object> cur) {
        if(target == 0){
            result.add(new ArrayList(cur));
            return;
        }
        if(i==candidates.length){
            return;
        }

        dfs(candidates,i+1,target,result,cur);

        if(target>=candidates[i]){
            cur.add(candidates[i]);
            dfs(candidates,i+1,target-candidates[i],result,cur);
            cur.remove(cur.size()-1);
        }
    }
}
